package com.kube.csv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CSVParser implements Parser {

	public Document parse(File file) {
		Document d = new CSVDocument();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = br.readLine()) != null) {
				d.addLine(parseLine(line));
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("File not found!", e);
		} catch (IOException e) {
			throw new RuntimeException("Problem reading file!", e);
		}
		return d;
	}
	
	private Line parseLine(String line) {
		Line l = new Line();
		StringBuffer sb = new StringBuffer();
		char previous = ' ';
		boolean inQuotes = false;
		for (int i = 0; i < line.length(); i++) {
			char theChar = line.charAt(i);
			// Create new element after comma (unless within quoted string)
			if (theChar == ',' && !inQuotes) {
				addElementFromStringBuffer(l, sb);
				sb = new StringBuffer();
			} else
			if (theChar == '"' && previous != '\\') {
				// Toggle inQoutes except where escaped
				inQuotes = !inQuotes;
			} else
			if (theChar == '\\') {
				// Ignore
			} else
			{
				sb.append(theChar);
			}
			previous = theChar;
		}
		// Last character, so save remaining text as final element
		addElementFromStringBuffer(l, sb);
		return l;
	}

	// Simple helper method
	private void addElementFromStringBuffer(Line l, StringBuffer sb) {
		l.add(new Element(sb.toString()));
	}
}
